/*
 * Copyright (C) 2005-2008 Alfresco Software Limited.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * 
 * As a special exception to the terms and conditions of version 2.0 of the GPL,
 * you may redistribute this Program in connection with Free/Libre and Open
 * Source Software ("FLOSS") applications as described in Alfresco's FLOSS
 * exception. You should have recieved a copy of the text describing the FLOSS
 * exception, and it is also available here:
 * http://www.alfresco.com/legal/licensing"
 */
package org.alfresco.confluence.plugins;

import java.util.Map;
import java.net.URLEncoder;

import com.atlassian.renderer.RenderContext;
import com.atlassian.renderer.v2.macro.MacroException;
import com.atlassian.confluence.util.http.HttpResponse;
import com.atlassian.confluence.setup.settings.SettingsManager;
import com.atlassian.spring.container.ContainerManager;

import org.alfresco.confluence.util.EnumAlfrescoServices;
import org.alfresco.confluence.util.ServiceUtils;

/**
 * Generate macro body based on the Alfresco CMIS service return.
 * 
 * @author Yong Qu
 *
 */
public class AlfrescoCMISMacro extends AlfrescoWSMacro
{

	/* (non-Javadoc)
	 * @see org.alfresco.confluence.plugins.AlfrescoWSMacro#execute(java.util.Map, java.lang.String, com.atlassian.renderer.RenderContext)
	 */
	public String execute(Map params, String body, RenderContext renderContext)
	throws MacroException
	{
		String op = (String) params.get("0");

		SettingsManager settingsManager = (SettingsManager) ContainerManager.getComponent("settingsManager");
		String baseURL = settingsManager.getGlobalSettings().getBaseUrl();

		try
		{
			HttpResponse response;

			StringBuffer alfServiceUrl = new StringBuffer();
			
			alfServiceUrl.append(baseURL);

			switch (EnumAlfrescoServices.fromValue(op)) {

			case REPO_INFO:

				alfServiceUrl.append(ServiceUtils.REPO_INFO_SERVICE_URL);
				break;

			case DOC:

				alfServiceUrl.append(ServiceUtils.DOC_SERVICE_URL);

				if ( params.containsKey("id")) {

					// try to find the noderef
					String nodeRef = (String) params.get("id");
					alfServiceUrl.append("?id=");
					alfServiceUrl.append(nodeRef);
					
				} else if (params.containsKey("path")) {

					// try to find the node path
					String nodePath = (String) params.get("path");
					alfServiceUrl.append("?path=");
					alfServiceUrl.append(URLEncoder.encode(nodePath));
				
				} else {	

					throw new MacroException("Invalid parameters for document service. Either id parameter or path parameter needs to be provided.") ;
				
				}
				
				break;
				
			case FOLDER:

				alfServiceUrl.append(ServiceUtils.FOLDER_SERVICE_URL);

				if ( params.containsKey("id")) {

					// try to find the noderef
					String nodeRef = (String) params.get("id");
					alfServiceUrl.append("?id=");
					alfServiceUrl.append(nodeRef);
					
				} else if (params.containsKey("path")) {

					// try to find the node path
					String nodePath = (String) params.get("path");
					alfServiceUrl.append("?path=");
					alfServiceUrl.append(URLEncoder.encode(nodePath));
				
				} else {	

					throw new MacroException("Invalid parameters for document service. Either id parameter or path parameter needs to be provided.") ;
				
				}
				
				break;
			case CONTENT:

				alfServiceUrl.append(ServiceUtils.CONTENT_SERVICE_URL);

				if ( params.containsKey("id")) {

					// try to find the noderef
					String nodeRef = (String) params.get("id");
					alfServiceUrl.append("?id=");
					alfServiceUrl.append(nodeRef);
					
				} else if (params.containsKey("path")) {

					// try to find the node path
					String nodePath = (String) params.get("path");
					alfServiceUrl.append("?path=");
					alfServiceUrl.append(URLEncoder.encode(nodePath));
				
				} else {	

					throw new MacroException("Invalid parameters for content service. Either id parameter or path parameter needs to be provided.") ;
				
				}
				
				break;

			case SEARCH:

				alfServiceUrl.append(ServiceUtils.SEARCH_SERVICE_URL);

				if ( params.containsKey("query")) {

					// try to find the noderef
					String query = (String) params.get("query");
					alfServiceUrl.append("?q=");
					alfServiceUrl.append(URLEncoder.encode(query));
					
				} else {
					
					throw new MacroException("Invalid parameters for search service. Query parameter to be provided.") ;
					
				}
					
				if (params.containsKey("startpage")) {

					// try to find the start page
					String startPage = (String) params.get("startpage");
					alfServiceUrl.append("&sp=");
					alfServiceUrl.append(URLEncoder.encode(startPage));
				
				} 
				
				if (params.containsKey("pageSize")) {

					// try to find the page size
					String pageSize = (String) params.get("pageSize");
					alfServiceUrl.append("&ps=");
					alfServiceUrl.append(URLEncoder.encode(pageSize));
				
				} 
				
				break;
			default:

				alfServiceUrl.append(ServiceUtils.REPO_INFO_SERVICE_URL);

			}
			
			// Common parameters
			// Check if the endpoint parameter is provided
			if (params.containsKey("endpoint")) {

				// try to find the repository endpoint
				String endpoint = (String) params.get("endpoint");
				alfServiceUrl.append("&endpoint=");
				alfServiceUrl.append(endpoint);
			
			}

			// Check if the view parameter is provided			
			if (params.containsKey("view")) {

				// try to find the view
				String view = (String) params.get("view");
				alfServiceUrl.append("&view=");
				alfServiceUrl.append(view);
			
			}
			
			response = getHttpRetrievalService().get(alfServiceUrl.toString());
			return ServiceUtils.getContent(response.getResponse());
		}
		catch(IllegalArgumentException e){
			throw new MacroException("Invalid service type. Valid options are "+EnumAlfrescoServices.values());
		}
		catch (Exception e)
		{
			throw new MacroException(e.getMessage());
		}

	}

}